﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Pibby.Core
{
	public static class HumanReadableDateInterpreter
	{
		public static string HowLongAgo(DateTime theDate)
		{
			return HumanReadableDateInterpreter.HowLongAgo(theDate, DateTime.Today);
		}

		public static string HowLongAgo(DateTime theDate, DateTime referenceDate)
		{
			if (theDate == null || theDate == DateTime.MinValue)
				return "Unknown";

			string text = string.Empty;
			
			TimeSpan delta = referenceDate - theDate;

			if (delta.Days == 0)
			{
				if (delta.Hours == 0)
				{
					if (delta.Minutes == 0)
						text = "Today";
					else if (delta.Minutes == 1)
						text = "1 minute ago";
					else
						text = string.Format(System.Globalization.CultureInfo.CurrentUICulture, "{0} minutes ago", delta.Minutes);
				}
				else
				{
					if (delta.Hours == 1)
						text = "1 hour ago";
					else if (delta.Hours > 0)
						text = string.Format(System.Globalization.CultureInfo.CurrentUICulture, "{0} hours ago", delta.Hours);
					else
						text = "Today";
				}
			}
			else if (delta.Days == 1)
				text = "Yesterday";
			else if (delta.Days < 8)
			{
				if (delta.Days > 0)
					text = string.Format(System.Globalization.CultureInfo.CurrentUICulture, "{0} days ago", delta.Days);
				else
				{
					// rss feeds sometimes like to publish in the future
					text = string.Format(System.Globalization.CultureInfo.CurrentUICulture, "In {0} more days", Math.Abs(delta.Days));
				}
			}
			else
			{
				int weeks = delta.Days / 7;

				if (weeks == 1)
				{
					text = "1 week ago";
				}
				else if (weeks <= 6)
					text = string.Format(System.Globalization.CultureInfo.CurrentUICulture, "{0} weeks ago", weeks);
				else
					text = theDate.ToLongDateString();
			}

			return text;
		}
	}
}
